package com.zwl.android.aidoctor;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import com.just.agentweb.AgentWeb;

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @author tcmaiok.org
 */
public class MainActivity extends AppCompatActivity {
    private String home_url = "https://www.myaiok.com/ai/doctor";
    public static final String ACTION_USB_PERMISSION = "com.zwl.USB_PERMISSION";
    private PendingIntent mPermissionIntent;
    private Button button_mai;
    private List<UsbDevice> devices = new ArrayList<>();//实体类
    private UsbManager usbManager;
    public static UsbDevice usbDevice = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        devices = getDeviceList();
        registerReceiver(MainActivity.this);

        TextView tv_mai = (TextView) findViewById(R.id.textView_mai);
        tv_mai.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tv_mai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (devices.size() == 0) {
                    Toast.makeText(MainActivity.this, "未连接脉象仪设备！", Toast.LENGTH_SHORT).show();
                    return;
                }
                final UsbDevice device = devices.get(0);
                if (device == null) return;

                usbDevice = device;
                Intent intent = new Intent(getApplicationContext(), DataActivity.class);
                startActivity(intent);
            }
        });

        LinearLayout view = findViewById(R.id.lview);
        AgentWeb mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(view, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go(home_url);

    }

    public void registerReceiver(Activity context) {
        mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        context.registerReceiver(mUsbReceiver, filter);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //tvInfo.append("BroadcastReceiver in\n");
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            // tvInfo.append("usb EXTRA_PERMISSION_GRANTED");
                            Toast.makeText(MainActivity.this, "授权成功！", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "授权失败！", Toast.LENGTH_SHORT).show();
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                // 有新的设备插入了，在这里一般会判断这个设备是不是我们想要的，是的话就去请求权限
                devices = getDeviceList();
                Toast.makeText(MainActivity.this, "有新的设备插入了！", Toast.LENGTH_SHORT).show();
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                // 有设备拔出了
                devices = getDeviceList();
                Toast.makeText(MainActivity.this, "有设备拔出了！", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public List<UsbDevice> getDeviceList() {
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        List<UsbDevice> usbDevices = new ArrayList<>();
        TextView tv_connhint = (TextView) findViewById(R.id.textViewConnHint);
        tv_connhint.setText("未连接");
        tv_connhint.setTextColor(Color.RED);
        while (deviceIterator.hasNext()) {
            UsbDevice device = deviceIterator.next();
            usbDevices.add(device);
            tv_connhint.setText("已连接");
            tv_connhint.setTextColor(Color.GREEN);
            //Toast.makeText(this, "找到 USB 设备接口:"+device.getDeviceName(), Toast.LENGTH_SHORT).show();
            //Log.e("USBUtil", "getDeviceList: " + device.getDeviceName());
        }
        return usbDevices;
    }
}
